var indexAlternateColor=0;

var alternateColor=Array("blue", "grey");

$(document).ready(function() {
    
    var jsonResult;
    var buildJSONStringFromValues="{";
            
    buildJSONStringFromValues+=convertToJson("action=read");
        
    buildJSONStringFromValues+=" }";        
        
    executeFeedQuery("tags",$.parseJSON(buildJSONStringFromValues));
    
    
    $("#requestFeed").click(function() {        
        var jsonResult;
        var buildJSONStringFromValues="{";
            
        buildJSONStringFromValues+=convertToJson($("#inputParam1").val());
        
        if ( (jsonResult=convertToJson($("#inputParam2").val()))!="") {
            buildJSONStringFromValues+=","+jsonResult;
        }            
        
        if ( (jsonResult=convertToJson($("#inputParam3").val()))!="") {
            buildJSONStringFromValues+=","+jsonResult;
        }            
        buildJSONStringFromValues+=" }";        
        console.log("var buildJSONStringFromValues = "+buildJSONStringFromValues);
        
        
            
        
        executeFeedQuery($("#inputFeed").val(),$.parseJSON(buildJSONStringFromValues));
    });
});

function convertToJson(keyValueString) {
    var parts;
    if ( (parts=keyValueString.split("=")) != "") {
        //        return parts[0]+':"'+parts[1]+'"';
        return '"'+parts[0]+'": "'+parts[1]+'"';
    }
    else {
        return "";
    }
}

//function requestFeed(strInputEntityToList) {
////    $.ajax({"url": buildUrlFromParams("list.php",strInputEntityToList) })
//$.ajax( {url: "ajax/tags.php?"+strInputEntityToList})
//    .success(function(data) { 
//        
// $("#outputResults").html($("#outputResults").html()+"<div style='color:"+alternateColor[indexAlternateColor]+"'><div>"+Date()+" :"+data+"</div><div>=========================================</div></div>");
// indexAlternateColor=(indexAlternateColor+1)%2;
//        
//
//    })
//    .error(function() {alert("error");});
////    .complete(function() { alert("complete"); });
//}

// the new ajax function, in POST method instead of GET one
// it takes a well formated JSON string, that contains the parameters for the web service 
function executeFeedQuery(feed,jsonParams) {
    $.post( 
    "ajax/"+feed+".php?",
    jsonParams)
    .success(function(data) { 

        $("#outputResults").html($("#outputResults").html()+"<div style='color:"+alternateColor[indexAlternateColor]+"'><div>"+Date()+" :"+data+"</div><div>=========================================</div></div>");
        indexAlternateColor=(indexAlternateColor+1)%2;  
        
        //line of code for scrolling to the bottom taken from http://kisdigital.wordpress.com/2009/11/12/using-jquery-to-scroll-to-the-bottom-of-a-div/
        //must back up! very useful, and straightforward
        $("#outputResults").attr({
            scrollTop: $("#outputResults").attr("scrollHeight")
        });
        
        if (feed=="tags") {
            feedTagsIntoSelect($.parseJSON(data).tags);
        }
        else if (feed=="bookmarks") {
            feedBookmarksIntoLinks($.parseJSON(data).bookmarks);
        }
        
    })
    .error(function() {
        alert("error");
    });
    //    .complete(function() { alert("complete"); });
}





////this is the former version of bookmarksBrowserSelectTags, coded as a html <select>
//function feedTagsIntoSelect(jsonTags) {
//    $("#bookmarksBrowserSelectTag").html("");
//    for (var i=0; i<jsonTags.length;i++) {
//        $("#bookmarksBrowserSelectTag").html($(this).html()+"<option value='"+jsonTags[i].id+"'>"+jsonTags[i].tag+"</option>");
//        
//        // below are 2 other more concise way of adding the option.Should work.. in theory ?
////        $("#bookmarksBrowserSelectTag").add("option").val(jsonTags[i].id).html(jsonTags[i].tag);
////$("#bookmarksBrowserSelectTag").append("<option></option>").val(jsonTags[i].id).html(jsonTags[i].tag);
//    }
//  
//}

//new version of bookmarksBrowserSelectTags, coded as a html <ul> list
function feedTagsIntoSelect(jsonTags) {
    
    $("#bookmarksBrowserSelectTag").html("<li>Select a tag</li>");
    
    for (var i=0; i<jsonTags.length;i++) {
        //the syntax below creates a closure in which context we can access the values of the tag's tag and id property for this loop's round
        (function(tagText, tagId) {
            
            
//            var newLi=$("<li>"+jsonTags[i].tag+"</li>")
//            .click(function(tagId) { feedBookmarksForTag(tagId);}(jsonTags[i].id));
//        
//            $("#bookmarksBrowserSelectTag").append(newLi);
        
            var newLi=$("<li>"+tagText+"</li>")
            .click(function() {fetchBookmarksForTag(tagId);});
            
            $("#bookmarksBrowserSelectTag").append(newLi);
            
                
            
        }(jsonTags[i].tag,jsonTags[i].id));
        
        // below are 2 other more concise way of adding the option.Should work.. in theory ?
        //        $("#bookmarksBrowserSelectTag").add("option").val(jsonTags[i].id).html(jsonTags[i].tag);
        //$("#bookmarksBrowserSelectTag").append("<option></option>").val(jsonTags[i].id).html(jsonTags[i].tag);
    }
  
}

function fetchBookmarksForTag(tagId) {
    console.log("fetching all bookmarks which have tag of id "+tagId);

var jsonResult;
    var buildJSONStringFromValues="{"+convertToJson("action=read")+","+convertToJson("tags-id="+tagId)+" }";        
        console.log(buildJSONStringFromValues);
    executeFeedQuery("bookmarks",$.parseJSON(buildJSONStringFromValues));
    
    
}

function feedBookmarksIntoLinks(jsonBookmarks) {
    
    if (jsonBookmarks.length>0) {
    $("#bookmarksBrowserBookmarks").html("<li>Select a bookmark</li>");
    
    for (var i=0;i<jsonBookmarks.length;i++) {
        (function(currentBookmark) {
            var newLi=$("<li />")
            .text(currentBookmark.title)
            .attr("title",currentBookmark.url)
            .click(function() {
               window.open(currentBookmark.url);
            });
            
            
            $("#bookmarksBrowserBookmarks").append(newLi);
            
            
            
        }(jsonBookmarks[i]));
    }
    
    }
    else {
        $("#bookmarksBrowserBookmarks").html("<li>Empty</li>");
    }
}